var formHelper = 
    {
        Stage : { Start: 1, ErrorReceived: 2, AllErrorsReceived: 3, NoErrors: 4 },
        
        submitForm : function(form, submitButtonName, errorCallback)
            {
                if (!errorCallback)
                    errorCallback = this.ajaxValidationErrorCallback;
                    
                var $form = $(form);

                errorCallback(formHelper.Stage.Start);

                $ProMesh.ValidateForm($form, function(valResult)
                    {
                        if (valResult.Success)
                        {
                            errorCallback(formHelper.Stage.NoErrors);
                            
                            if (submitButtonName && submitButtonName.length > 0)
                                $("<input type='hidden' value='*' />").prependTo($form).attr("name", submitButtonName).val($("input[name=" + submitButtonName + "]").val());
                
                            $form.submit();
                            
                            return;
                        }   
            
                        $.each(valResult.Messages, function(i,msg) { errorCallback(formHelper.Stage.ErrorReceived, msg.Message , msg.ControlNames); });
            
                        errorCallback(formHelper.Stage.AllErrorsReceived);
                    });
            }
            ,
        ajaxValidationErrorCallback: function(phase, errorMsg , fieldNames)
            {
                var $valSummary = $(".ValidationSummary ul");
    
                if (phase == formHelper.Stage.Start)
                {
                    $valSummary.parent().hide();
                    $valSummary.empty();

                    $("form .Error").removeClass("ErrorBox");
                    
                    return;
                }
    
                if (phase == formHelper.Stage.ErrorReceived)
                {
                    $("<li>").appendTo($valSummary).text(errorMsg);

                    $.each(fieldNames, function(i, name) { $("input[name=" + name + "]").addClass("ErrorBox"); });
                    
                    return;
                }
                
                if (phase == formHelper.Stage.AllErrorsReceived)
                {
                    $valSummary.parent().fadeIn("medium");
                    
                    return;
                }
            }
            ,
        bindButton : function(button)
            {
                $(button).click( function() {  formHelper.submitForm($(button)[0].form, $(button).attr("name")); return false;  } );
            }
    }
